/**
 * 
 */
package edu.scsu.csci.config;

import java.lang.annotation.Annotation;

import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

import edu.scsu.csci.IValidator;

 
/**
 * XStream Convertor for validator.
 * 
 * @author Maqbool Khan
 * @since jdk 1.5
 * @see
 * @viz.diagram ValidatorXmlConvertor.tpx
 */
public class ValidatorXmlConvertor implements Converter {

	/**
	 * Can it convert this class type?
	 * 
	 * @see com.thoughtworks.xstream.converters.Converter#canConvert(java.lang.Class)
	 */
	public boolean canConvert(Class clazz) {
		return clazz.equals(ConfigValidatorWrapper.class);
	}

	/* (non-Javadoc)
	 * @see com.thoughtworks.xstream.converters.Converter#marshal(java.lang.Object, com.thoughtworks.xstream.io.HierarchicalStreamWriter, com.thoughtworks.xstream.converters.MarshallingContext)
	 */
	public void marshal(Object value, HierarchicalStreamWriter writer,
				MarshallingContext context) {
		ConfigValidatorWrapper object = (ConfigValidatorWrapper) value;
		writer.startNode("type");
		writer.setValue(object.getObjectType().getName());
		writer.endNode();
		writer.startNode("validatorClass");
		writer.setValue(object.getValidatorClazz().getName());
		writer.endNode();
		writer.startNode("annotationClass");
		writer.setValue(object.getAnnotaionClazz().getName());
		writer.endNode();
	}
	
	/* (non-Javadoc)
	 * @see com.thoughtworks.xstream.converters.Converter#unmarshal(com.thoughtworks.xstream.io.HierarchicalStreamReader, com.thoughtworks.xstream.converters.UnmarshallingContext)
	 */
	public Object unmarshal(HierarchicalStreamReader reader,
				UnmarshallingContext context) {
		try {
			ConfigValidatorWrapper object = new ConfigValidatorWrapper();
			reader.moveDown();
			Class type = Class.forName(reader.getValue());
			object.setObjectType(type);
			reader.moveUp();
			reader.moveDown();
			Class<? extends IValidator> validatorClass = 
				(Class<? extends IValidator>) Class.forName(reader.getValue().trim());
			object.setValidatorClazz(validatorClass);
			reader.moveUp();
			reader.moveDown();
			Class<? extends Annotation> annotationClazz = 
				(Class<? extends Annotation>) Class.forName(reader.getValue().trim());
			object.setAnnotaionClazz(annotationClazz);
			reader.moveUp();
			return object;
		} catch (ClassCastException e) {
			throw new RuntimeException(e.getMessage(), e);
		} catch (ClassNotFoundException e) {
			throw new ConversionException(e.getMessage(), e);
		}
	}
}
